import { FileType, GetNasFileListParams, GetNasFileListResponse } from '@global/types'
import { debounce, throttle } from 'lodash'
import { reactive, toRefs, watch, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useApi } from '@/api'
import { useMusic } from '@/store/useMusic'

export default () => {
  const route = useRoute()
  const api = useApi()
  const music = useMusic()

  const state = reactive({
    /** 获取文件列表接口的参数 */
    params: {
      page: 1,
      size: 28,
      fileType: route.meta.fileType,
      parentPath: route.query.parentPath
    } as GetNasFileListParams,

    /** 文件列表 */
    fileData: {
      page: 1,
      list: [],
      total: 0
    } as GetNasFileListResponse
  })

  const changeGetFileListSize = () => {
    const fileItemEl = document.querySelector('[file-id]') as HTMLElement
    const fileWrapperEl = document.querySelector('[file-wrapper]') as HTMLElement
    const { width: widthItem, height: heightItem } = fileItemEl.getClientRects()[0]
    // eslint-disable-next-line prefer-const
    let { width: widthWrapper, height: heightWrapper } = fileWrapperEl.getClientRects()[0]
    widthWrapper -= 8
    const rows = ~~(heightWrapper / heightItem)
    const cols = ~~(widthWrapper / widthItem)
    let total = rows * cols
    if (total > 100) total = 100
    state.params.size = total
  }
  const changeGetFileListSizeDebounce = debounce(changeGetFileListSize, 1000)
  onMounted(() => {
    changeGetFileListSize()
    window.addEventListener('resize', changeGetFileListSizeDebounce)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', changeGetFileListSizeDebounce)
  })

  // 监听路由更新获取列表的参数
  watch(route, route => {
    state.params.parentPath = (route.query.parentPath as string) || ''
    state.params.fileType = route.meta.fileType as FileType
    state.params.page = 1
  })

  /** 获取文件列表 */
  const getFileList = async (loading = true) => {
    state.fileData = await api.get('/nas/list', { params: state.params, loading })
    // 如果时查询音乐文件列表，顺带更新 pinia 音乐列表
    if (state.params.fileType === FileType.audio) music.$patch({ musicList: state.fileData.list })
  }
  // 监听参数更新文件列表
  watch(state.params, () => getFileList(), { immediate: true })

  /** 防抖获取文件列表 */
  const getFileListThrottle = throttle(async () => {
    state.fileData = await api.get('/nas/list', {
      params: state.params,
      loading: false
    })
  }, 500)

  return {
    ...toRefs(state),
    getFileList,
    getFileListThrottle
  }
}
